import {SysMenuTree} from "@/api/sys/SysMenuApi";
import {computed} from "vue";
import store from "@/store";

export function changeNavMenu(path: string) {
    let allMenuList = computed<SysMenuTree[]>(() => store.state.localStorage.menuList)
    let navMenuList = computed<SysMenuTree[]>(() => store.state.sessionStorage.navMenuList)
    let urlPathMenu = getMenuByPath(path, allMenuList.value);
    if (urlPathMenu === undefined) {
        navMenuList.value.forEach(value => value.isNavActive = false);
        return;
    }
    let selected = navMenuList.value.filter(value => value.path === urlPathMenu?.path).at(0);
    for (const menu of navMenuList.value) {
        menu.isNavActive = false;
    }
    if (selected === undefined) {
        navMenuList.value.push(urlPathMenu);
        urlPathMenu.isNavActive = true;
    } else {
        selected.isNavActive = true;
    }
    store.commit("sessionStorage/navMenuList", navMenuList.value)
}


export let result: SysMenuTree | undefined;

export function getMenuByPath(path: string, list: SysMenuTree[], status?: any) {
    if (status === undefined) {
        result = undefined;
        status = 1;
    }
    if (result == undefined) {
        for (const sysMenuTree of list) {
            if (sysMenuTree.path === path) {
                result = sysMenuTree;
            } else if (sysMenuTree.children != undefined && sysMenuTree.children.length > 0) {
                getMenuByPath(path, sysMenuTree.children, status);
            }
        }
    }
    return result;
}


export function changeHeader(path: string) {
    let menuList = computed<SysMenuTree[]>(() => store.state.localStorage.menuList);
    for (const sysMenuTree of menuList.value) {
        sysMenuTree.isHeaderActive = false;
    }
    let activeMenu = getLevel1ByPath(path, menuList.value)
    if (!activeMenu || activeMenu.length === 0) {
        return;
    }
    let hasActive = false;
    for (const sysMenuTree of activeMenu) {
        if (!hasActive && sysMenuTree.isHeaderActive) {
            hasActive = true;
        } else {
            sysMenuTree.isHeaderActive = false;
        }

    }
    store.commit("localStorage/menuList", activeMenu);
}


export function getLevel1ByPath(path: string, list?: SysMenuTree[], level1?: SysMenuTree) {
    if (list && list.length > 0) {
        for (const sysMenuTree of list) {
            if (sysMenuTree.path === path && level1 != undefined) {
                level1.isHeaderActive = true;
            } else {
                getLevel1ByPath(path, sysMenuTree.children, level1 === undefined ? sysMenuTree : level1);
            }
        }
    }
    return list;
}